package com.smugmugsoftware.airconcalc.advanced;

import android.app.AlertDialog;
import android.app.Dialog;
import android.support.v4.app.DialogFragment;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnKeyListener;
import android.content.Intent;
import android.content.DialogInterface.OnClickListener;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.Html;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.TextView;

public class InformationDialog extends DialogFragment {

	public static final int NO_LOAD_WALL = 12001;
	public static final int NO_LOAD_CELFLOOR = 12002;
	public static final int NO_LOAD_SENSIBLE = 12003;
	public static final int FIRST_RUN = 12004;
	public static final int BETA_WARNING = 12005;
	public static final int WALL_HELP = 12006;
	//	public static final int WINDOOR_HELP = 12007;
	public static final int CELFLOOR_HELP = 12008;
	public static final int SENSIBLE_HELP = 12009;
	public static final int LOCALE_HELP = 12010;
	public static final int NEW_ROOM_FIRST_RUN = 12011;
	public static final int LOCALE_FIRST_RUN = 12012;
	public static final int REPORT_FIRST_RUN = 12013;
	public static final int CHART_FIRST_RUN = 12014;

	private SharedPreferences prefs;

	private Context context;
	private DialogFragment thisDialog;

	private int type;
	private String showAgainTag;

	public InformationDialog() {}

	public InformationDialog(Context context, int type, String showAgainTag) {
		this.thisDialog = this;
		this.context = context;
		this.type = type;
		this.showAgainTag = showAgainTag;
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setRetainInstance(true);

		prefs = getActivity().getSharedPreferences("config.dat", Context.MODE_PRIVATE);
	}

	@Override
	public Dialog onCreateDialog(Bundle savedInstanceState) {

		final AlertDialog.Builder builder = new AlertDialog.Builder(context);
		LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		final View thisView = inflater.inflate(R.layout.information_dialog, null);

		boolean uncancelable = false;

		if (showAgainTag == null) {
			thisView.findViewById(R.id.show_again_check_box).setVisibility(View.GONE);
		}

		TextView message = (TextView) thisView.findViewById(R.id.message);

		if (type == NO_LOAD_WALL) {
			builder.setTitle("No Load");
			message.setText("This wall has no cooling load.\n\nWalls adjacent to other conditioned spaces or below grade have no effect on the cooling load of a room or structure.\n\nTo save time, only factor external walls that are above grade into your cooling load calculation.");

		} else if (type == NO_LOAD_CELFLOOR) {
			builder.setTitle("No Load");
			message.setText("This ceiling/floor has no cooling load.\n\nCeilings below another conditioned space (like a finished second story) and floors directly adjacent to the ground have no effect on the cooling load of a room or structure.\n\nTo save time, only factor in ceilings adjacent to an unconditioned attic/roof or floors over unconditioned spaces such as an exposed crawlspace or unfinished garage.");			

		} else if (type == NO_LOAD_SENSIBLE) {
			builder.setTitle("No Load");
			message.setText("This object has an effective cooling load of zero.\n\nIf it is extremely low power or is typically not in use during hours of peak cooling, it is recommended that you do not include it in your cooling calculation.");

		} else if (type == FIRST_RUN) {
			builder.setTitle("Welcome!");
			message.setText(Html.fromHtml("Welcome to the Advanced A/C Calculator (A<sup>2</sup>/C<sup>2</sup>)!<br><br>This app allows you to calculate the cooling needs of a structure using data and formulas similar to the ones professional HVAC installers use.<br><br>Unlike basic calculators, A<sup>2</sup>/C<sup>2</sup> is a powerful and flexible tool, using advanced algorithms to take into account indoor/outdoor temperature relationships, sun angle, and air infiltration.<br><br>The first time you view a screen, an informational dialog like this will pop up to give you basic instructions.<br><br>For additional information, contextual help icons are available for pertinent topics.  For additional information, please contact our development or support teams by email.<br><br>BETA NOTICE:<br><br>A<sup>2</sup>/C<sup>2</sup> is currently in PUBLIC BETA.  By using this calculator, you are helping us in our endeavor to make it as powerful, easy-to-use, and bug-free as possible.<br><br>Our developers are currently using all of their free time to optimize code and squash bugs.  If you run into problems, have suggestions, or have useful data that will improve the quality of A<sup>2</sup>/C<sup>2</sup> for all users, please don't hesitate to contact our developers directly."));

			addContactDevsButton(builder);
			addSupportButton(builder);

			uncancelable = true;

		} else if (type == BETA_WARNING) {
			builder.setTitle("BETA NOTICE");
			message.setText(Html.fromHtml("A<sup>2</sup>/C<sup>2</sup> is currently in PUBLIC BETA.  By using this calculator, you are helping us in our endeavor to make it as powerful, easy-to-use, and bug-free as possible.<br><br>Our developers are currently using all of their free time to optimize code and squash bugs.  If you run into problems, have suggestions, or have useful data that will improve the quality of A<sup>2</sup>/C<sup>2</sup> for all users, please don't hesitate to contact our developers directly."));

			addContactDevsButton(builder);

			uncancelable = true;

		} else if (type == WALL_HELP) {
			builder.setTitle("Walls");

			((ImageView) thisView.findViewById(R.id.help_image)).setImageResource(R.drawable.wall_help);
			message.setText("You ONLY need to measure portions of the walls that are above grade and exposed to an unconditioned environment.  You can measure interior and below grade sections of wall, but they will not have an effect on the load calculation.\n\nFor maximum compatibility with traditional methods, the construction number system in this app is as close to the ACCA numbering/lettering system as possible. If you do not have access to ACCA construction number tables, use the wizard to browse our database of known wall configurations.");

		} else if (type == CELFLOOR_HELP) {
			builder.setTitle("Ceilings and Floors");

			((ImageView) thisView.findViewById(R.id.help_image)).setImageResource(R.drawable.celfloor_help);
			message.setText("You ONLY need to measure portions of ceilings and floors exposed to an unconditioned environment.  You can measure ceilings below conditioned floors and vice versa, but they will not have an effect on the load calculation.  The same goes for floors at/below grade (adjacent to the ground)\n\nFor maximum compatibility with traditional methods, the construction number system in this app is as close to the ACCA numbering/lettering system as possible. If you do not have access to ACCA construction number tables, use the wizard to browse our database of known ceiling/floor configurations.");

		} else if (type == SENSIBLE_HELP) {
			builder.setTitle("Sensible Loads");

			message.setText("Only consider load sources that will be both PRESENT and IN USE at the time of maximum heating (typically between 4-6pm)\n\nOnly count the total number of occupants that will be PRESENT in this room at the time of maximum heating.\n\nLoad data is calculated from data found in official ASHRAE tables.  If there is an appliance/commercial load that is not included in our database, contact our developers and we will do what we can do accomodate your request.  If you are able to provide us with official sensible load data, we will be more than happy to add it directly to our database.");

			addContactDevsButton(builder);

		} else if (type == LOCALE_HELP) {
			builder.setTitle("Locale");

			message.setText("Your locale is defined as a set of environmental parameters used in a load calculation\n\nIf you are unsure what your local environmental paramaters are, the \"Get Local Conditions\" button will allow you to choose a nearby city (US and Canada only) and load a set of scientifically measured conditions.\n\nCan't find your locale?  We are constantly looking to expand our database.  If you would like to add to our locale database, contact our developers.  We are looking for people with access to data tables or the equipment to perform dry bulb temperature range and water vapor measurements at 50%/55% relative humidity.");
			addContactDevsButton(builder);

		} else if (type == LOCALE_FIRST_RUN) {
			builder.setTitle("The Global Values Editor");

			message.setText("Here, you can change values that affect the load calculation as a whole.  You can:\n\n - Add the name of the estimator and street address of the calculation for recordkeeping purposes.\n - Define the construction tightness of the building\n - Define environmental parameters and indoor design temperate (55% RH is assumed indoors)\n\nIf you are unsure what your environmental paramaters are, the \"Get Local Conditions\" button will allow you to choose a nearby city (US and Canada only) and load a set of scientifically measured environmental conditions.");

			addContactDevsButton(builder);

		} else if (type == NEW_ROOM_FIRST_RUN) {
			builder.setTitle("The Room Editor");

			message.setText("NOTICE: YOU ONLY NEED TO MEASURE BUILDING ELEMENTS ADJACENT TO THE ENVIRONMENT OR UNCONDITIONED SPACES!\n\nWith this editor, you can build the structure one room at a time, taking into account all exterior-facing features and internal heat sources.\n\nIn most rooms, this will only be 1-2 walls, windows, and a ceiling.  Unless the floor is directly over an unconditioned space or exposed to the environment, it does not need to be entered.\n\nYou may enter building features that are not exposed to the environment, but you will be warned that these components will not have an effect on the building's cooling load.");

		} else if (type == CHART_FIRST_RUN) {
			builder.setTitle("The Chart Screen");

			message.setText("Here, you are can break down a building's load distribution by room, by cooling load source, or break down each room by source.\n\nThe chart screen allows you to find a building's hotspots and load distribution at a glance, empowering you to take action and reduce the cooling load of your hottest rooms through passive means (e.g.: external solar screens on windows)");

		} else if (type == REPORT_FIRST_RUN) {
			builder.setTitle("The Report Screen");

			message.setText("Here, the app will generate a complete list of the building's load sources and their BTU contribution to the total cooling load.  The building is broken down into rooms, and each room is futher broken down by source, allowing you to conduct a detailed analysis of the total load calculation.");

		} 

		builder.setNegativeButton("Dismiss", new OnClickListener() {

			public void onClick(DialogInterface dialog, int which) {

				if (showAgainTag != null) {
					prefs.edit().putBoolean(showAgainTag, ((CheckBox) thisView.findViewById(R.id.show_again_check_box)).isChecked()).commit();
				}

				thisDialog.dismiss();
			}
		});

		builder.setView(thisView);
		AlertDialog returnDialog = builder.create();

		if (uncancelable) {
			returnDialog.setCanceledOnTouchOutside(false);
			returnDialog.setCancelable(false);
		}

		returnDialog.setOnKeyListener(new OnKeyListener() {
			public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
				if (keyCode == KeyEvent.KEYCODE_BACK) {
					if (type == FIRST_RUN || type == BETA_WARNING) {
						// do nothing
						return true;
					} else {
						thisDialog.dismiss();
						return true;
					}
				}
				return false;
			}
		});

		return returnDialog;
	}

	private void addContactDevsButton(final AlertDialog.Builder builder) {
		builder.setNeutralButton("Email the Developers", new OnClickListener() {

			public void onClick(DialogInterface dialog, int which) {
				thisDialog.dismiss();

				Intent intent = new Intent(Intent.ACTION_SEND);   
				intent.putExtra(Intent.EXTRA_EMAIL, new String[] { "developers@smugmugsoftware.com" });   
				intent.putExtra(Intent.EXTRA_SUBJECT, "Advanced Calculator: " );  

				intent.setType("message/rfc822");  
				startActivity(intent);   
			}
		});
	}

	private void addSupportButton(final AlertDialog.Builder builder) {
		builder.setPositiveButton("Contact Support", new OnClickListener() {

			public void onClick(DialogInterface dialog, int which) {
				thisDialog.dismiss();

				Intent intent = new Intent(Intent.ACTION_SEND);   
				intent.putExtra(Intent.EXTRA_EMAIL, new String[] { "support@smugmugsoftware.com" });   
				intent.putExtra(Intent.EXTRA_SUBJECT, "Advanced Calc Support: " );  

				intent.setType("message/rfc822");  
				startActivity(intent);   
			}
		});
	}

	public int getType() {
		return type;
	}
}
